package cn.cdzdjd.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.PipiGXService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class PipiGXServiceImpl implements PipiGXService {
	private final String baseUrl = "https://h5.pipigx.com/ppapi/share/fetch_content";
	private final String imageBaseUrl = "https://file.ippzone.com/img/png/id/";
	@Resource
	private RestTemplate restTemplate;

	@Override
	public VideoInfoVO getVideoInfo(String locationUrl) {
		try {
			Map<String, String> params = UrlUtil.convertUrlParamsToMap(new URL(locationUrl));
			Map<String, Object> param = new HashMap<>();
			param.put("pid", Long.valueOf(params.get("pid")));
			param.put("mid", Long.valueOf(params.get("mid")));
			param.put("type", "post");
			String result = restTemplate.postForObject(baseUrl, param, String.class);
			JSONObject json = new JSONObject(result);
			if (json.getInt("ret") == 1) {
				JSONObject post = json.getJSONObject("data").getJSONObject("post");
				String title = post.getString("content");
				// 如果有videos的key，说明是视频
				if (post.has("videos")) {
					long imgId = post.getJSONArray("imgs").getJSONObject(0).getLong("id");
					JSONObject videos = post.getJSONObject("videos");
					JSONObject video = videos.getJSONObject(imgId + "");
					String videoUrl = video.getString("url");
					String posterUrl = imageBaseUrl + imgId;
					List<String> posterList = new ArrayList<>();
					posterList.add(UrlUtil.setHttps(posterUrl));
					List<String> videoList = new ArrayList<>();
					videoList.add(UrlUtil.setHttps(videoUrl));
					return new VideoInfoVO(videoList, posterList, title, null);
				} else {
					JSONArray imgs = post.getJSONArray("imgs");
					List<String> posterList = new ArrayList<>();
					for (int i = 0; i < imgs.length(); i++) {
						long id = imgs.getJSONObject(i).getLong("id");
						String posterUrl = imageBaseUrl + id;
						posterList.add(UrlUtil.setHttps(posterUrl));
					}
					return new VideoInfoVO(null, posterList, title, null);
				}
			} else {
				throw new RenException(ErrorCode.PARSE_ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RenException(ErrorCode.PARSE_ERROR);
		}
	}

}
